package cn.wolfcode.crm.web.controlleradvice;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ExceptionControllerAdvice {

    private static MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();

    @ExceptionHandler(UnauthorizedException .class)
    public ModelAndView handleUnauthorizedException(Exception e , HandlerMethod handlerMethod){
        e.printStackTrace();
        return ExceptionControllerAdvice.getModelAndView(e,handlerMethod,"common/nopermission","UnauthorizedException:你个吊毛,没有权限,不要乱搞...");

    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e , HandlerMethod handlerMethod){
        e.printStackTrace();
        return ExceptionControllerAdvice.getModelAndView(e,handlerMethod,"common/error","Exception:系统繁忙,正在殴打程序员中...");
    }

    private static ModelAndView getModelAndView(Exception e , HandlerMethod handlerMethod,String viewsName,String exceptionMsg){
        //通过判断这个方法上面有没有@ResponseBody这个注解,来判断响应的是数据还是
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        ModelAndView mv = new ModelAndView();
        if(methodAnnotation == null){
            //响应视图文件
            mv.setViewName(viewsName);
            mv.addObject("e",e);
            return mv;
        }else{
            //响应json数据,响应异常的错误数据回去页面
            Map<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("msg",exceptionMsg);
            mv = new ModelAndView(mappingJackson2JsonView,map);
            return mv;
        }
    }
}
